#!/bin/bash

# 服务管理脚本 - 支持安装和卸载（支持脚本参数）

show_usage() {
    echo "用法:"
    echo "  sudo ./service_manager.sh install <服务名> <脚本路径> [参数1] [参数2] ..."
    echo "  sudo ./service_manager.sh uninstall <服务名>"
    echo "  sudo ./service_manager.sh status <服务名>"
    echo "  sudo ./service_manager.sh logs <服务名>"
    echo ""
    echo "示例:"
    echo "  sudo ./service_manager.sh install gpu-monitor ./my_script.sh"
    echo "  sudo ./service_manager.sh install gpu-monitor ./my_script.sh --port 8080"
    echo "  sudo ./service_manager.sh install gpu-monitor ./my_script.sh --config /etc/gpu.conf --debug"
    echo "  sudo ./service_manager.sh uninstall gpu-monitor"
    echo "  sudo ./service_manager.sh status gpu-monitor"
    echo "  sudo ./service_manager.sh logs gpu-monitor"
}

install_service() {
    if [ $# -lt 2 ]; then
        echo "错误：至少需要服务名和脚本路径"
        show_usage
        exit 1
    fi
    
    SERVICE_NAME=$1
    SCRIPT_PATH=$2
    shift 2  # 移除前两个参数，剩下的都是脚本参数
    SCRIPT_ARGS="$@"  # 获取所有剩余参数
    
    # 获取脚本绝对路径
    SCRIPT_PATH=$(realpath "$SCRIPT_PATH")
    
    # 检查脚本是否存在
    if [ ! -f "$SCRIPT_PATH" ]; then
        echo "错误：脚本文件不存在: $SCRIPT_PATH"
        exit 1
    fi
    
    # 设置脚本执行权限
    chmod +x "$SCRIPT_PATH"
    echo "✓ 脚本执行权限已设置"
    
    # 获取脚本目录
    SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
    
    # 构建完整的执行命令
    if [ -n "$SCRIPT_ARGS" ]; then
        EXEC_COMMAND="$SCRIPT_PATH $SCRIPT_ARGS"
        echo "✓ 服务将使用参数: $SCRIPT_ARGS"
    else
        EXEC_COMMAND="$SCRIPT_PATH"
        echo "✓ 服务无额外参数"
    fi
    
    # 创建服务文件
    SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
    
    echo "正在创建服务文件: $SERVICE_FILE"
    
    cat > "$SERVICE_FILE" << EOF
[Unit]
Description=$SERVICE_NAME Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$SCRIPT_DIR
ExecStart=$EXEC_COMMAND
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
    
    echo "✓ 服务文件已创建"
    
    # 重新加载systemd
    systemctl daemon-reload
    echo "✓ systemd已重新加载"
    
    # 启用服务（开机自启）
    systemctl enable "$SERVICE_NAME"
    echo "✓ 服务已启用: $SERVICE_NAME"
    
    # 启动服务
    systemctl start "$SERVICE_NAME"
    echo "✓ 服务已启动: $SERVICE_NAME"
    
    echo ""
    echo "🎉 服务 $SERVICE_NAME 安装成功!"
    echo ""
    echo "服务信息:"
    echo "  脚本路径: $SCRIPT_PATH"
    echo "  工作目录: $SCRIPT_DIR"
    echo "  执行命令: $EXEC_COMMAND"
    echo ""
    echo "管理命令:"
    echo "  sudo systemctl start $SERVICE_NAME      # 启动服务"
    echo "  sudo systemctl stop $SERVICE_NAME       # 停止服务"
    echo "  sudo systemctl restart $SERVICE_NAME    # 重启服务"
    echo "  sudo systemctl status $SERVICE_NAME     # 查看状态"
    echo "  sudo journalctl -u $SERVICE_NAME -f     # 查看实时日志"
    echo "  sudo journalctl -u $SERVICE_NAME --since today  # 查看今天的日志"
    echo ""
    
    # 显示服务状态
    echo "当前服务状态:"
    systemctl status "$SERVICE_NAME" --no-pager -l
}

uninstall_service() {
    SERVICE_NAME=$1
    
    echo "正在卸载服务: $SERVICE_NAME"
    
    # 停止服务
    systemctl stop "$SERVICE_NAME" 2>/dev/null
    echo "✓ 服务已停止: $SERVICE_NAME"
    
    # 禁用服务
    systemctl disable "$SERVICE_NAME" 2>/dev/null
    echo "✓ 服务已禁用: $SERVICE_NAME"
    
    # 删除服务文件
    SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
    if [ -f "$SERVICE_FILE" ]; then
        rm "$SERVICE_FILE"
        echo "✓ 服务文件已删除: $SERVICE_FILE"
    else
        echo "! 服务文件不存在: $SERVICE_FILE"
    fi
    
    # 重新加载systemd
    systemctl daemon-reload
    echo "✓ systemd已重新加载"
    
    echo ""
    echo "🎉 服务 $SERVICE_NAME 卸载成功!"
}

show_status() {
    SERVICE_NAME=$1
    echo "服务状态: $SERVICE_NAME"
    echo "========================"
    systemctl status "$SERVICE_NAME" --no-pager -l
}

show_logs() {
    SERVICE_NAME=$1
    echo "服务日志: $SERVICE_NAME"
    echo "========================"
    echo "最近20条日志:"
    journalctl -u "$SERVICE_NAME" --no-pager -l -n 20
    echo ""
    echo "实时日志 (按Ctrl+C退出):"
    journalctl -u "$SERVICE_NAME" -f
}

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "错误：需要root权限运行此脚本"
    echo "请使用: sudo $0 $*"
    exit 1
fi

# 检查参数数量
if [ $# -lt 1 ]; then
    show_usage
    exit 1
fi

# 解析命令
case "$1" in
    install)
        if [ $# -lt 3 ]; then
            echo "错误：install命令至少需要服务名和脚本路径"
            show_usage
            exit 1
        fi
        shift  # 移除第一个参数 (install)
        install_service "$@"  # 传递所有剩余参数
        ;;
    uninstall)
        if [ $# -ne 2 ]; then
            echo "错误：uninstall命令需要服务名"
            show_usage
            exit 1
        fi
        uninstall_service "$2"
        ;;
    status)
        if [ $# -ne 2 ]; then
            echo "错误：status命令需要服务名"
            show_usage
            exit 1
        fi
        show_status "$2"
        ;;
    logs)
        if [ $# -ne 2 ]; then
            echo "错误：logs命令需要服务名"
            show_usage
            exit 1
        fi
        show_logs "$2"
        ;;
    *)
        echo "错误：未知命令 '$1'"
        show_usage
        exit 1
        ;;
esac

